const fs = require('fs');
const { writeFile } = require('../app/util');

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout,
});

function careateTemplate(templateName) {
  var fs = require('fs');
  var copy = function (src, dst) {
    let paths = fs.readdirSync(src); //同步读取当前目录
    paths.forEach(function (path) {
      var _src = src + '/' + path;
      var _dst = dst + '/' + path;
      fs.stat(_src, function (err, stats) {
        //stats  该对象 包含文件属性
        if (err) throw err;
        if (stats.isFile()) {
          //如果是个文件则拷贝
          let readable = fs.createReadStream(_src); //创建读取流
          let writable = fs.createWriteStream(_dst); //创建写入流
          readable.pipe(writable);
        } else if (stats.isDirectory()) {
          //是目录则 递归
          checkDirectory(_src, _dst, copy);
        }
      });
    });
  };
  var checkDirectory = function (src, dst, callback) {
    fs.access(dst, fs.constants.F_OK, (err) => {
      if (err) {
        fs.mkdirSync(dst);
        callback(src, dst);
      } else {
        callback(src, dst);
      }
    });
  };

  checkDirectory('./config/template', `./src/theme/${templateName}`, copy);
}

function queryInputTemplateName() {
  readline.question('请输入模版名称', (templateName) => {
    fs.readdir('./src/theme', (err, dir) => {
      if (dir.some((el) => templateName === el)) {
        console.log('模版存在请重新输入');
        queryInputTemplateName();
      } else {
        writeFile(
          './config.json',
          `{"root": "${templateName}","buildRoot": "./theme","isGitPush":true,"buildStaticRoot": "assets"}`
        );
        careateTemplate(templateName);
        close();
      }
    });
  });
}

function close() {
  readline.close();
}

exports.create = function () {
  queryInputTemplateName('请输入模版名称');
};
